/**
 *  Copyright 26.08.2012 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.geolessi.srv;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import de.xelerity.geolessi.preferences.Preferences;
import de.xelerity.geolessi.srv.impl.haltestelle.bahn.LinienProHaltestelleGetter;

public class CacheService<T> {

	String namespace;
	static Map<Integer, MemcacheService> allCache = new HashMap<Integer, MemcacheService>();
	static Log log = LogFactory.getLog(LinienProHaltestelleGetter.class);

	@SuppressWarnings("unused")
	private CacheService() {

	}

	public CacheService(String pUniqueNamespace) {

		if (!Preferences.useMemCache)
			return;

		if (pUniqueNamespace == null)
			pUniqueNamespace = "null";
		namespace = pUniqueNamespace.trim();
		MemcacheService cache = allCache.get(namespace.hashCode());
		if (cache == null) {
			cache = MemcacheServiceFactory.getMemcacheService(namespace);
			allCache.put(namespace.hashCode(), cache);
		}
	}

	@SuppressWarnings("unchecked")
	public T get(int key) {

		if (!Preferences.useMemCache)
			return null;

		try {
			MemcacheService cache = allCache.get(namespace.hashCode());
			return cache == null ? null : (T) cache.get(key);
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	public void put(int key, T value) {
		if (!Preferences.useMemCache)
			return;

		try {
			if (value != null) {
				MemcacheService cache = allCache.get(namespace.hashCode());
				if (cache != null)
					cache.put(key, value);
			}
			return;
		} catch (Throwable e) {
			log.error(e.getMessage(), e);
		}
	}
}
